package com.homejoy.system.service.impl;

import java.util.List;

import com.homejoy.common.enums.AgreementStatus;
import com.homejoy.common.enums.RentStatus;
import com.homejoy.common.utils.DateUtils;
import com.homejoy.common.utils.SecurityUtils;
import com.homejoy.system.domain.HomejoyProperty;
import com.homejoy.system.mapper.HomejoyPropertyMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.homejoy.system.mapper.HomejoyPropertyPendingMapper;
import com.homejoy.system.domain.HomejoyPropertyPending;
import com.homejoy.system.service.IHomejoyPropertyPendingService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 待办管理Service业务层处理
 *
 * @author homeJoy
 * @date 2025-11-15
 */
@Service
public class HomejoyPropertyPendingServiceImpl implements IHomejoyPropertyPendingService {

    @Resource
    private HomejoyPropertyPendingMapper homejoyPropertyPendingMapper;

    @Resource
    private HomejoyPropertyMapper homejoyPropertyMapper;

    /**
     * 查询待办管理
     *
     * @param pendingId 待办管理主键
     * @return 待办管理
     */
    @Override
    public HomejoyPropertyPending selectHomejoyPropertyPendingByPendingId(Long pendingId) {
        return homejoyPropertyPendingMapper.selectHomejoyPropertyPendingByPendingId(pendingId);
    }

    /**
     * 查询待办管理列表
     *
     * @param homejoyPropertyPending 待办管理
     * @return 待办管理
     */
    @Override
    public List<HomejoyPropertyPending> selectHomejoyPropertyPendingList(HomejoyPropertyPending homejoyPropertyPending) {
        List<HomejoyPropertyPending> homejoyPropertyPendings = homejoyPropertyPendingMapper.selectHomejoyPropertyPendingList(homejoyPropertyPending);
        homejoyPropertyPendings.forEach(c -> {
            c.setPropertyTitle(homejoyPropertyMapper.selectHomejoyPropertyByPropertyId(c.getPropertyId()).getPropertyTitle());
        });
        return homejoyPropertyPendings;
    }

    /**
     * 新增待办管理
     *
     * @param homejoyPropertyPending 待办管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertHomejoyPropertyPending(HomejoyPropertyPending homejoyPropertyPending) {
        String username = SecurityUtils.getUsername();
        Long propertyId = homejoyPropertyPending.getPropertyId();
        // 参数校验
        if (propertyId == null) {
            throw new RuntimeException("房源ID不能为空");
        }
        // 查询房源信息
        HomejoyProperty property = homejoyPropertyMapper.selectHomejoyPropertyByPropertyId(propertyId);
        if (property == null) {
            throw new RuntimeException("房源不存在");
        }
        // 校验：房东不能点击租用自己的房源
        if (property.getCreateBy().equals(username)) {
            throw new RuntimeException("出租者请勿点击！");
        }
        // 校验房源状态
        if (property.getRentStatus() == 2) {
            throw new RuntimeException("该房源已出租，无法发起租用");
        }
        if (property.getRentStatus() == 3) {
            throw new RuntimeException("该房源正在处理中，请勿重复操作");
        }
        // 检查是否存在未完成的待办
        HomejoyPropertyPending existingPending = checkExistingPending(propertyId, username, property.getCreateBy());
        if (existingPending != null) {
            return handleExistingPending(existingPending, homejoyPropertyPending);
        }
        // 设置房源为预租状态
        HomejoyProperty updateProperty = new HomejoyProperty();
        updateProperty.setPropertyId(propertyId);
        updateProperty.setRentStatus(3); // 预租状态
        homejoyPropertyMapper.updateHomejoyProperty(updateProperty);
        // 设置待办信息
        homejoyPropertyPending.setLandlord(property.getCreateBy());
        homejoyPropertyPending.setTenant(username);
        homejoyPropertyPending.setLandlordAgreed("0"); // 待处理
        homejoyPropertyPending.setTenantAgreed("0");   // 待处理
        homejoyPropertyPending.setStatus("1");         // 待房东同意
        homejoyPropertyPending.setCreateBy(username);
        homejoyPropertyPending.setCreateTime(DateUtils.getNowDate());
        return homejoyPropertyPendingMapper.insertHomejoyPropertyPending(homejoyPropertyPending);
    }

    private HomejoyPropertyPending checkExistingPending(Long propertyId, String tenant, String landlord) {
        // 查询该房源相关的待办记录
        List<HomejoyPropertyPending> pendingList = homejoyPropertyPendingMapper.selectHomejoyPropertyPendingList(
                new HomejoyPropertyPending() {{setPropertyId(propertyId);}});
        if (pendingList != null && !pendingList.isEmpty()) {
            for (HomejoyPropertyPending pending : pendingList) {
                // 检查是否存在相同租客和房东的未完成待办
                if (pending.getTenant().equals(tenant) &&pending.getLandlord().equals(landlord) && !isPendingCompleted(pending)) {
                    return pending;
                }
            }
        }
        return null;
    }

    /**
     * 判断待办是否已完成
     */
    private boolean isPendingCompleted(HomejoyPropertyPending pending) {
        // 状态为3(已完成)或4(已取消)表示已完成
        return "3".equals(pending.getStatus()) || "4".equals(pending.getStatus());
    }

    /**
     * 处理已存在的待办记录
     */
    private int handleExistingPending(HomejoyPropertyPending existingPending, HomejoyPropertyPending newPending) {
        // 如果待办已完成，抛出异常
        if (isPendingCompleted(existingPending)) {
            throw new RuntimeException("您已处理过该房源的租用申请");
        }
        // 如果待办未完成，更新待办信息（重置双方同意状态）
        existingPending.setLandlordAgreed("0");
        existingPending.setTenantAgreed("0");
        existingPending.setStatus("1"); // 重置为待房东同意
        existingPending.setUpdateTime(DateUtils.getNowDate());
        existingPending.setUpdateBy(SecurityUtils.getUsername());
        // 如果有其他需要更新的字段，可以在这里设置---👇
        return homejoyPropertyPendingMapper.updateHomejoyPropertyPending(existingPending);
    }

    /**
     * 检查双方是否都同意
     */
    private boolean checkBothAgreed(HomejoyPropertyPending propertyPending) {
        return AgreementStatus.AGREED.getCode().equals(propertyPending.getLandlordAgreed()) &&
                AgreementStatus.AGREED.getCode().equals(propertyPending.getTenantAgreed());
    }

    /**
     * 更新房源状态为已出租
     */
    private void updatePropertyRentStatus(Long propertyId) {
        HomejoyProperty property = new HomejoyProperty();
        property.setPropertyId(propertyId);
        property.setRentStatus(RentStatus.RENTED.getCode());
        homejoyPropertyMapper.updateHomejoyProperty(property);
    }


    /**
     * 处理待办同意操作
     *
     * @param homejoyPropertyPending 待办信息
     * @param userType               用户类型 (landlord/tenant)
     * @return
     */
    public int handleAgreement(HomejoyPropertyPending homejoyPropertyPending, String userType) {
        // 参数校验
        if (homejoyPropertyPending == null || homejoyPropertyPending.getPendingId() == null) {
            throw new RuntimeException("待办信息不能为空");
        }
        // 查询待办信息
        HomejoyPropertyPending propertyPending = homejoyPropertyPendingMapper.selectHomejoyPropertyPendingByPendingId(homejoyPropertyPending.getPendingId());
        if (propertyPending == null) {
            throw new RuntimeException("待办信息不存在");
        }
        // 权限校验
        String currentUser = SecurityUtils.getUsername();
        String newStatus = propertyPending.getStatus(); // 初始化为当前状态
        if ("landlord".equals(userType)) {
            if (!propertyPending.getLandlord().equals(currentUser)) {
                throw new RuntimeException("请勿操作他人待办!");
            }
            // 检查是否已经操作过
            if (StringUtils.isNotEmpty(propertyPending.getLandlordAgreed()) &&
                    !AgreementStatus.PENDING.getCode().equals(propertyPending.getLandlordAgreed())) {
                throw new RuntimeException("您已经操作过该待办!");
            }
            // 更新出租者同意状态
            propertyPending.setLandlordAgreed(homejoyPropertyPending.getLandlordAgreed());
            //如果房东拒绝，重置房源状态
            if ("2".equals(homejoyPropertyPending.getLandlordAgreed())) {
                newStatus="4"; // 已取消
                resetPropertyStatus(propertyPending.getPropertyId());
            }else if ("1".equals(homejoyPropertyPending.getLandlordAgreed())) {
                // 房东同意，检查租客状态
                if ("0".equals(propertyPending.getTenantAgreed()) || propertyPending.getTenantAgreed() == null) {
                    newStatus = "2"; // 待租客同意
                } else if ("1".equals(propertyPending.getTenantAgreed())) {
                    newStatus = "3"; // 双方都同意，已完成
                } else if ("2".equals(propertyPending.getTenantAgreed())) {
                    newStatus = "4"; // 租客已拒绝，已取消
                }
            }
        } else if ("tenant".equals(userType)) {
            if (!propertyPending.getTenant().equals(currentUser)) {
                throw new RuntimeException("请勿操作他人待办!");
            }
            // 检查是否已经操作过
            if (StringUtils.isNotEmpty(propertyPending.getTenantAgreed()) &&
                    !AgreementStatus.PENDING.getCode().equals(propertyPending.getTenantAgreed())) {
                throw new RuntimeException("您已经操作过该待办!");
            }
            // 更新租用者同意状态
            propertyPending.setTenantAgreed(homejoyPropertyPending.getTenantAgreed());
            //如果租客拒绝，重置房源状态
            if ("2".equals(homejoyPropertyPending.getTenantAgreed())) {
                newStatus="4"; // 已取消
                resetPropertyStatus(propertyPending.getPropertyId());
            }else if ("1".equals(homejoyPropertyPending.getTenantAgreed())) {
                // 租客同意，检查房东状态
                if ("0".equals(propertyPending.getLandlordAgreed()) || propertyPending.getLandlordAgreed() == null) {
                    newStatus = "1"; // 待房东同意
                } else if ("1".equals(propertyPending.getLandlordAgreed())) {
                    newStatus = "3"; // 双方都同意，已完成
                } else if ("2".equals(propertyPending.getLandlordAgreed())) {
                    newStatus = "4"; // 房东已拒绝，已取消
                }
            }
        } else {
            throw new RuntimeException("无效的用户类型");
        }
        //状态
        propertyPending.setStatus(newStatus);
        // 检查是否双方都已同意
        if (checkBothAgreed(propertyPending)) {
            updatePropertyRentStatus(propertyPending.getPropertyId());
            propertyPending.setStatus("3"); // 确保状态为已完成
        }
        // 更新待办信息
        return homejoyPropertyPendingMapper.updateHomejoyPropertyPending(propertyPending);
    }


    /**
     * 重置房源状态为可租
     */
    private void resetPropertyStatus(Long propertyId) {
        HomejoyProperty property = new HomejoyProperty();
        property.setPropertyId(propertyId);
        property.setRentStatus(1); // 可租
        homejoyPropertyMapper.updateHomejoyProperty(property);
    }



    /**
     * 出租者点击同意
     *
     * @param homejoyPropertyPending
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int landlordAgreed(HomejoyPropertyPending homejoyPropertyPending) {
        // 参数校验
        if (homejoyPropertyPending.getLandlordAgreed() == null) {
            throw new RuntimeException("请选择同意或拒绝");
        }
        return handleAgreement(homejoyPropertyPending, "landlord");
    }


    /**
     * 租用者点击同意
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int tenantAgreed(HomejoyPropertyPending homejoyPropertyPending) {
        // 参数校验
        if (homejoyPropertyPending.getTenantAgreed() == null) {
            throw new RuntimeException("请选择同意或拒绝");
        }
        return handleAgreement(homejoyPropertyPending, "tenant");
    }



    /**
     * 修改待办管理
     *
     * @param homejoyPropertyPending 待办管理
     * @return 结果
     */
    @Override
    public int updateHomejoyPropertyPending(HomejoyPropertyPending homejoyPropertyPending) {
        homejoyPropertyPending.setUpdateTime(DateUtils.getNowDate());
        return homejoyPropertyPendingMapper.updateHomejoyPropertyPending(homejoyPropertyPending);
    }

    /**
     * 批量删除待办管理
     *
     * @param pendingIds 需要删除的待办管理主键
     * @return 结果
     */
    @Override
    public int deleteHomejoyPropertyPendingByPendingIds(Long[] pendingIds) {
        return homejoyPropertyPendingMapper.deleteHomejoyPropertyPendingByPendingIds(pendingIds);
    }

    /**
     * 删除待办管理信息
     *
     * @param pendingId 待办管理主键
     * @return 结果
     */
    @Override
    public int deleteHomejoyPropertyPendingByPendingId(Long pendingId) {
        return homejoyPropertyPendingMapper.deleteHomejoyPropertyPendingByPendingId(pendingId);
    }
}
